#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
 
#define MSG_NAME "./msg_file"
 
/*struct msgbuf // 先定义消息的结构体 --- 必须要有两个成员
{
    long mtype;
    char mtext[1024];
};*/
 
int main(int argc, char const *argv[])
{
    key_t key;
    int msgid;
 
    key = ftok(MSG_NAME, 'k');
    msgid = msgget(key, 0655 | IPC_CREAT);
 
    printf("key = %x\n", key); // key 值相同生成的消息队列也相同
    printf("msgid = %d\n", msgid);
 
    char buffer[1024];
    long mtype;
    struct msgbuf pmsgbuf;
    size_t size;
 
    while (1)
    {
        memset(buffer, 0, sizeof(buffer));
        memset(&pmsgbuf, 0, sizeof(struct msgbuf));
        size = msgrcv(msgid, &pmsgbuf, sizeof(pmsgbuf), 3, 0); // 接收要指定ID(消息队列的标识符)
        if (size < 0)
        {
            perror("msg rcv error");
            exit(1);
        }
        else
        {
            printf("recv data: %s\n", pmsgbuf.mtext);
        }

        //printf("recv data: %s\n", pmsgbuf.mtext);
    }
 
    return 0;
}
